<template>
  <div>
    <div class="native_container">
      <div class="gameContainer">
        <div class="gameName">{{ currentScriptInfo?.scriptName }}</div>
      </div>
      <div class="menu-container">
        <el-button @click="showModal('DirectoryManagement')"
          >目录管理
        </el-button>
        <el-button @click="showModal('ItemManagement')">物品管理</el-button>
        <el-button @click="showModal('ArchivesManagement')">档案管理</el-button>
        <el-button @click="showModal('AchievementManagement')"
          >成就管理
        </el-button>
        <el-button @click="showModal('EndingManagement')">结局管理</el-button>
        <el-button @click="showModal('CharacterManagement')"
          >角色管理
        </el-button>
      </div>
      <div class="buttonClass">
        <button class="save-button" @click="saveConfig">保存配置</button>
        <button class="exit-button" @click="exitEdit">退出编辑</button>
      </div>
      <div class="menu_dialog">
        <!-- 动态组件渲染 -->
        <Dialog :visible="isModalVisible" :close="closeModal">
          <component :is="currentModal" v-if="currentModal" />
        </Dialog>
      </div>
    </div>
    <div class="edit_area" @click="hideContextMenu">
      <div class="preview_container">
        <div class="part1">
          <el-select
            v-model="sort"
            placeholder="Select"
            @change="handleSelected(sort, options)"
          >
            <el-option
              v-for="item in options"
              :key="item.sort"
              :label="item.label"
              :value="item.sort"
            />
          </el-select>
        </div>
        <div class="part2" @contextmenu.prevent="showContextMenu">

          
          <!-- 上下文菜单 -->
          <div
            v-show="contextMenuVisible"
            class="context-menu"
            :style="{
              top: contextMenuPosition.top + 'px',
              left: contextMenuPosition.left + 'px'
            }"
          >
            <div
              class="menu-item"
              :class="{ selected: selectedMenuItem === 'upinsert' }"
              @mouseenter="showSubMenu('upinsert')"
              @mouseleave="hideSubMenu('insert')"
            >
              向上插入
              <div
                v-show="subMenuVisible.upinsert"
                ref="subMenuUpinsert"
                :class="subMenuClass.upinsert"
                @mouseleave="hideSubMenu('upinsert')"
              >
                <div
                  v-for="insertOption in insertOptions.up"
                  :key="insertOption"
                  :class="{ selected: secondMenuItem === insertOption }"
                  @click="insertModule(insertOption, 'up','')"
                  @mouseover="showSubMenuItem(insertOption)"
                  @mouseleave="hideSecondMenu('upinsert')"
                >
                  {{ insertOption }}
                </div>
              </div>
            </div>
            <div
              class="menu-item"
              :class="{ selected: selectedMenuItem === 'downinsert' }"
              @mouseenter="showSubMenu('downinsert')"
              @mouseleave="hideSubMenu('insert')"
            >
              向下插入
              <div
                v-show="subMenuVisible.downinsert"
                class="sub-menu-underinsert"
                @mouseleave="hideSubMenu('downinsert')"
              >
                <div
                
                  v-for="insertOption in insertOptions.down"
                  :key="insertOption"
                  :class="{ selected: secondMenuItem === insertOption }"
                  @mouseover="showSubMenuItem(insertOption)"
                  @mouseleave="hideSecondMenu('downinsert')"
                  @click="insertModule(insertOption, 'down','')"
                >
                  {{ insertOption }}
                </div>
              </div>
            </div>
            <div
              class="menu-item"
              :class="{ selected: selectedMenuItem === 'delete' }"
              @mouseenter="showSubMenu('delete')"
              @mouseleave="hideSubMenu('delete')"
              @click="deleteContainer"
            >
              删除模块
            </div>
          </div>

          <div
            v-for="(component, index) in components"
            :key="index"
            class="component_combine"
            @click="componentClickEvent(component)"
            @contextmenu.prevent="handleRightEvent(component, index)"
          >
            <div class="edit_component" v-if="(component.showFlag === undefined || component.showFlag === true )">
              <div
                v-if="(!component.isDisabled === true)"
                class="component_index"
                :style="{
                  backgroundColor:
                    selectedIndex === component.componentSort
                      ? '#ff8d1a'
                      : 'transparent',
                  color:
                    selectedIndex === component.componentSort ? '#000' : '#fff'
                }"
              >
                <div class="component-index-id">
                  {{ component.id }}
                </div>
                <div
                  v-if="
                    (component.name === '选择' || component.name === '答题') &&
                    isShowCycleIcon &&
                    selectedIndex === component.componentSort
                  "
                  class="circle-contain"
                >
                  <div>
                    <img
                      src="/svg/circle.svg"
                      style="width: 20px; height: 20px"
                    />
                  </div>
                  <div>{{ circleNode }}</div>
                </div>
              </div>
              <div class="component_type">
                <component
                  :is="componentMap[component.name]"
                  v-if="
                    !component.isDisabled === true &&
                    component.name !== '选择' &&
                    component.name !== '答题'
                  "
                  :id="isSelectedComponet.id"
                  :valueFromParent="getComponentValue(component.componentSort)"
                />
                <component
                  :is="componentMap[component.name]"
                  v-if="
                    !component.isDisabled === true &&
                    (component.name === '选择' || component.name === '答题')
                  "
                  :id="isSelectedComponet.id"
                  :valueFromParent="getComponentValue(component.componentSort)"
                  @childSelect1="handleChildrenSelectedEvent"
                />
              </div>
            </div>
          </div>

          <button  @click="quickInsert('文本')">添加</button>
      

          
        </div>
      </div>
      <div class="editor_component">
        <component
          :is="editComponentMap[isSelectedComponet.name]"
          :id="isSelectedComponet.id"
          :isChildSelected="isChildSelected"
          :valueFromParent="componentJson?.chapter[selectedIndex]"
          :sort="sort"
          :currentSort="components_next_number - 1"
          @save="handleSaveContent"
        />
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import {
  ref,
  defineAsyncComponent,
  shallowRef,
  onMounted,
  watch,
  nextTick,
  computed
} from "vue";
import Text from "./components/Text.vue";
import PictureEditor from "./editComponents/PictureEditor.vue";
import TextEditor from "./editComponents/TextEditor.vue";
import Picture from "@/views/gamemanage/game-edit/components/Picture.vue";
import Video from "@/views/gamemanage/game-edit/components/Video.vue";
import VideoEditor from "@/views/gamemanage/game-edit/editComponents/VideoEditor.vue";
import Audio from "@/views/gamemanage/game-edit/components/Audio.vue";
import AudioEditor from "@/views/gamemanage/game-edit/editComponents/AudioEditor.vue";
import Chapter from "@/views/gamemanage/game-edit/components/Chapter.vue";
import ChapterEditor from "@/views/gamemanage/game-edit/editComponents/ChapterEditor.vue";
import Select from "@/views/gamemanage/game-edit/components/Select.vue";
import SelectEditor from "@/views/gamemanage/game-edit/editComponents/SelectEditor.vue";
import Ending from "@/views/gamemanage/game-edit/components/Ending.vue";
import EndingEditor from "@/views/gamemanage/game-edit/editComponents/EndingEditor.vue";
import Reward from "@/views/gamemanage/game-edit/components/Reward.vue";
import RewardEditor from "@/views/gamemanage/game-edit/editComponents/RewardEditor.vue";
import Dialogue from "@/views/gamemanage/game-edit/components/Dialogue.vue";
import DialogueEditor from "@/views/gamemanage/game-edit/editComponents/DialogueEditor.vue";
import QuestionAnswer from "@/views/gamemanage/game-edit/components/QuestionAnswer.vue";
import QuestionAnswerEditor from "@/views/gamemanage/game-edit/editComponents/QuestionAnswerEditor.vue";
import Dialog from "./menu/Dialog.vue";
import { useRoute, useRouter } from "vue-router";
import { useScriptStore } from "@/store/modules/script";
import { useChapterStore } from "@/store/modules/chapterInfo";
import { getDirectoryById } from "@/api/directory";
import { useDirectoryStore } from "@/store/modules/directory";
import { getContentByChapterId, updateContentByChapterId } from "@/api/chapter";
import { ElMessage } from "element-plus";
import { message } from "@/utils/message";
import { isNull } from "@pureadmin/utils";
import { el } from "@faker-js/faker";

const route = useRoute();
const router = useRouter();
// 定义一个对象，存储向上和向下插入的模块种类

const scriptId = route.query.scriptId;
const chapterId = ref(1);
// 动态导入弹出框组件
// 当前弹出的模态框组件名
const currentModal = shallowRef<any>(null);
const isModalVisible = ref<boolean>(false);
const directoryStore = useDirectoryStore();
const isChildSelected = ref(0);
const circleNode = ref("");

// 显示对应的模态框
const showModal = (modalName: string) => {
  currentModal.value = defineAsyncComponent(
    () => import(`./menu/${modalName}.vue`)
  );
  isModalVisible.value = true;
};

const currentScriptInfo = ref({});
// 关闭模态框
const closeModal = () => {
  isModalVisible.value = false;
  currentModal.value = null;
};
const selectedMenuItem = ref("");

const components = ref([]);
//数据库存的
const originComponents = ref([]);
const moduleOptions = {
  Text: "文本",
  Picture: "图片",
  Video: "视频",
  Audio: "音频",
  Chapter: "章节",
  Select: "选择",
  Ending: "结局",
  Reward: "奖励",
  Dialogue: "对话",
  QuestionAnswer: "答题"
};

// 定义模块种类的配置项
const componentMap = {
  文本: Text,
  图片: Picture,
  视频: Video,
  音频: Audio,
  章节: Chapter,
  选择: Select,
  结局: Ending,
  奖励: Reward,
  对话: Dialogue,
  答题: QuestionAnswer

  // 其他组件的映射关系
};
const editComponentMap = {
  文本: TextEditor,
  图片: PictureEditor,
  视频: VideoEditor,
  音频: AudioEditor,
  章节: ChapterEditor,
  选择: SelectEditor,
  结局: EndingEditor,
  奖励: RewardEditor,
  对话: DialogueEditor,
  答题: QuestionAnswerEditor

  // 其他组件的映射关系
};
// 统计被禁用的组件的数字
const disabledCount = computed(() => {
  return componentJson.value.chapter.filter(item => item.isDisabled).length;
});

const tableData = ref([]);
const maxSort = ref(0);

const selectedIndex = ref(0);
const isSelectedComponet = ref({});
// 定义一个对象，存储向上和向下插入的模块种类
const insertOptions = ref({
  up: moduleOptions, // 向上插入的模块种类
  down: moduleOptions // 向下插入的模块种类
});
const componentJson: Object = ref({
  chapter: []
});
const sort = ref(1);
const options = ref([
  {
    sort: 1,
    label: "第一章 默认章节名称"
  }
]);

const subMenuClass = ref({ upinsert: "sub-menu", downinsert: "sub-menu" });
const subMenuUpinsert = ref(null);
const subMenuDowninsert = ref(null);

const adjustSubMenuPosition = type => {
  const menuElement =
    type === "upinsert" ? subMenuUpinsert.value : subMenuDowninsert.value;
  if (menuElement) {
    const { top, height } = menuElement.getBoundingClientRect();
    const windowHeight = window.innerHeight;
    if (top + height > windowHeight) {
      subMenuClass.value[type] = "sub-menu-up";
    } else {
      subMenuClass.value[type] = "sub-menu";
    }
  }
};

const isEndingChapterFlag = ref(false);


//选则组件点击了一个选项
const handleChildrenSelectedEvent = (item: any) => {
  //第一遍 先让没选中的不显示
  componentJson.value.chapter[item.parent].moduleValue.value.forEach(element => {
    if(item.selectResult !=  element.selectResult){
        notShowMark(element.selectResult)
    }
  });

  //第二遍 让选中的显示
   componentJson.value.chapter[item.parent].moduleValue.value.forEach(element => {
    if(item.selectResult ==  element.selectResult){
        isChildSelected.value = item.id -1;//控制样式
        showMark(item.selectResult)
    }
  });

 
};

const showMark = (nodeId: String) =>{
  
  let nodeIndex =  components.value.findIndex(item => item.id === nodeId);

  if(nodeIndex !== -1){
    //节点已经标记为true，进入循环
    if(components.value[nodeIndex].showFlag && components.value[nodeIndex].showFlag === true){
      return;
    }
    //节点存在 标记为不显示
    components.value[nodeIndex].showFlag=true;

    //找到下一个节点
    let moduleType = componentJson.value.chapter[nodeIndex].moduleType;
    if('Select'===moduleType){
      componentJson.value.chapter[nodeIndex].moduleValue.value.forEach(element => {
        notShowMark(element.selectResult)
      });
    }else if('QuestionAnswer'===moduleType){
      componentJson.value.chapter[nodeIndex].moduleValue.value.forEach(element => {
        notShowMark(element.selectResult)
      });
    }else{
      if(componentJson.value.chapter[nodeIndex].moduleNext) {
        console.log('下一个节点'+componentJson.value.chapter[nodeIndex].moduleNext)
        showMark(componentJson.value.chapter[nodeIndex].moduleNext)
      }
    }
  }
}

const notShowMark = (nodeId: String) =>{
  
  let nodeIndex =  components.value.findIndex(item => item.id === nodeId);
  if(nodeIndex !== -1){
    //节点已经标记为false，进入循环
    if(components.value[nodeIndex].showFlag && components.value[nodeIndex].showFlag === false){
      return;
    }
    //节点存在 标记为不显示
    components.value[nodeIndex].showFlag=false;

    //找到下一个节点
    let moduleType = componentJson.value.chapter[nodeIndex].moduleType;
    if('Select'===moduleType){
      componentJson.value.chapter[nodeIndex].moduleValue.value.forEach(element => {
        notShowMark(element.selectResult)
      });
    }else if('QuestionAnswer'===moduleType){
      componentJson.value.chapter[nodeIndex].moduleValue.value.forEach(element => {
        notShowMark(element.selectResult)
      });
    }else{
      if(componentJson.value.chapter[nodeIndex].moduleNext) {
        notShowMark(componentJson.value.chapter[nodeIndex].moduleNext)
      }
    }
  }
}

//丢失的节点
const lostMark = (nodeId: String) =>{
  
  let nodeIndex =  components.value.findIndex(item => item.id === nodeId);
  if(nodeIndex !== -1){
    //节点已经标记为删除，进入循环
    if(components.value[nodeIndex].isDisabled && components.value[nodeIndex].isDisabled === true){
      return;
    }
    //节点存在 标记为删除
    components.value[nodeIndex].isDisabled=true;

    //找到下一个节点
    let moduleType = componentJson.value.chapter[nodeIndex].moduleType;
    if('Select'===moduleType){  
      componentJson.value.chapter[nodeIndex].moduleValue.value.forEach(element => {
        lostMark(element.selectResult)
      });
    }else if('QuestionAnswer'===moduleType){
      componentJson.value.chapter[nodeIndex].moduleValue.value.forEach(element => {
        lostMark(element.selectResult)
      });
    }else{
      if(componentJson.value.chapter[nodeIndex].moduleNext) {
        lostMark(componentJson.value.chapter[nodeIndex].moduleNext)
      }
    }
  }
}




const isShowCycleIcon = ref(false);
const secondMenuItem = ref("");

const showSubMenuItem = menu => {
  secondMenuItem.value = menu;
  selectedMenuItem.value = "";
};

//  文本、对话等组件内容编辑完成点保存
const handleSaveContent = (content: Object) => {

  componentJson.value.chapter[content.sort] = content;
  originComponents.value[content.sort] = content;
  // 找到他moduleNext的sort值
  let moduleNextNode = components.value.find(
    item => item.id === content.moduleNext
  );

  //似乎在展示循环logo
  if (moduleNextNode) {
    if (moduleNextNode.componentSort < content?.sort) {
      //   说明在他前面 就显示循环图标
      isShowCycleIcon.value = true;
      circleNode.value = content.moduleNext;
    } else {
      isShowCycleIcon.value = false;
    }
  } else {
    isShowCycleIcon.value = false;
  }

  //如果是选择节点直接给他创建了
  if('Select' === content.moduleType || 'QuestionAnswer' === content.moduleType){
    components_next_number.value = components_next_number.value + content.moduleValue.value.length -1;
    content.moduleValue.value.forEach(item => {
      //判断存在
      let findIndex = components.value.findIndex(itemB => itemB.id === item.selectResult)
      if(findIndex === -1){
        insertSelectModule(item.moduleType, 'down',item.selectResult)
        notShowMark(item.selectResult)
      }
    });
  }


  //遇到选择或者答题的时候会出现childSelectedIndex
  // let childSelectedIndex = componentJson.value.chapter[content.sort]["selectIndex"];
  // if (!isNaN(childSelectedIndex) && componentJson.value.chapter[content.sort]["moduleValue"]["value"][childSelectedIndex]) {
  //   //   只有有这个index 并且 存在这个index指向的值 获取 下一节点
  //   let selectResult = componentJson.value.chapter[content.sort]["moduleValue"]["value"][childSelectedIndex]["selectResult"];


  //   //    判断是否存在节点,定位他的位置
  //   let findIndex = -1;
  //   if(originComponents.value.length >= 1 ){
  //     findIndex = originComponents.value.findIndex(item => item.moduleId === selectResult && !item.isDisabled);
  //   }
    
  //   if (findIndex !== -1) {
  //     let findItem = originComponents.value[findIndex];
  //     if (findItem.sort < content.sort) {
  //       const chapterArray = Object.values(componentJson.value.chapter);
  //       componentJson.value.chapter = [];
  //       // 移除从找到的元素之后的所有元素
  //       components.value = components.value.slice(0, content.sort + 1);
  //       // 将 chapter 对象的值转换为数组
  //       const newChapterArray = chapterArray.slice(0, content.sort + 1);
  //       // 将新的数组转换回对象
  //       newChapterArray.forEach((item, index) => {componentJson.value.chapter[index] = item;});
  //     } else {
  //       let array = originComponents.value;
  //       // 将数组转换为 dataMap，键为 moduleId
  //       const dataMap = array.reduce((map, obj) => {
  //         map[obj.moduleId] = obj;
  //         return map;
  //       }, {});
 
  //       let startIndex = content.sort;
  //       let selectedIndex = findItem.sort;
  //       const endIndex = ref(0);
  //       let rankArray = [];
  //       rankArray.push(startIndex);
  //       console.log("打印排序过的数组");
  //       console.log(rankArray);
  //       let tempCompareNumber = startIndex;
  //       // 如果选择的节点超过一个 就开始处理
  //       if (content.moduleValue.value.length > 0) {
  //         for (let i = 0; i < content.moduleValue.value.length; i++) {
  //           if (content.moduleValue.value[i].selectResult in dataMap) {
  //             if (
  //               dataMap[content.moduleValue.value[i].selectResult].sort >
  //               tempCompareNumber
  //             ) {
  //               rankArray.push(
  //                 dataMap[content.moduleValue.value[i].selectResult].sort
  //               );
  //               tempCompareNumber =
  //                 dataMap[content.moduleValue.value[i].selectResult].sort;
  //             } else {
  //               rankArray.splice(
  //                 1,
  //                 0,
  //                 dataMap[content.moduleValue.value[i].selectResult].sort
  //               );
  //             }
  //           }
  //         }
  //       }
  //       // 判断选择的那个分支是什么在什么位置
  //       if (rankArray.length === 2 && rankArray[1] == selectedIndex) {
  //         // console.log("说明数组没别人了就他两,那就不用处理");
  //       }
  //       if (rankArray.length > 2) {
  //         if (rankArray[rankArray.length - 1] == selectedIndex) {
  //           // console.log("说明他是数组中最大的元素,直接把他两中间的嘎了");
  //           // 计算需要删除的元素数量，不包含 startIndex 和 selectedIndex
  //           const deleteCount = selectedIndex - startIndex - 1;
  //           let copyComponent = components.value;
  //           // 确保删除范围在数组长度内
  //           if (
  //             deleteCount > 1 &&
  //             startIndex + 1 + deleteCount <= components.value.length
  //           ) {
  //             copyComponent.splice(startIndex + 1, deleteCount);
  //             components.value = copyComponent;
  //           } else {
  //             // console.log("删除范围超出数组长度，删除操作未执行");
  //           }
  //         } else {
  //           let findSelectIndex = rankArray.findIndex(
  //             item => item === selectedIndex
  //           );
  //           components.value.splice(rankArray[rankArray.length - 1]);
  //         }
  //       }
  //     }
  //   }
  // }
};

const saveConfig = () => {
  //   保存到数据库里面
  if (route.query.chapterId) {
    chapterId.value = Number(route.query.chapterId);
  }
  const chapterNum = "chapter";
  const data = {
    id: directoryStore.directoryList[chapterId.value - 1].id,
    content: {}
  };
  // 先移除现有的 headFlag 和 endFlag
  // let componentJsonArray = componentJson.value.chapter;
  let componentJsonArray = originComponents.value;
  componentJsonArray.forEach(item => {
    delete item.headFlag;
    delete item.endFlag;
  });
  // 打标头文件和局部文件
  let foundHead = false;
  for (let i = 0; i < componentJsonArray.length; i++) {
    if (!foundHead) {
      componentJsonArray[i].headFlag = true;
      foundHead = true;
    }
  }
  for (let i = componentJsonArray.length - 1; i >= 0; i--) {
    if (!componentJsonArray[i].isDisabled) {
      componentJsonArray[i].endFlag = true;
      break;
    }
  }
  data.content[chapterNum] = componentJsonArray;
  data.content = JSON.stringify(data.content);
  updateContentByChapterId(data)
    .then(res => {
      if (res.code === "0000") {
        ElMessage({
          message: "游戏章节编辑成功.",
          type: "success"
        });
      } else {
        ElMessage.error(res.message);
      }
    })
    .catch(err => {
      ElMessage.error(err.response);
    });
};

const refreshDirectory = (scriptId: number) => {
  tableData.value = [];
  getDirectoryById(scriptId).then(res => {
    const directoryList = res.data?.list;
    for (let i = 0; i < directoryList?.length; i++) {
      tableData.value.push({
        id: directoryList[i].id,
        sort: directoryList[i].sort,
        sequence: directoryList[i].sequence,
        title: directoryList[i].title,
        status: directoryList[i].status
      });
      if (directoryList[i].sort > maxSort.value) {
        maxSort.value = directoryList[i].sort;
      }
    }
    directoryStore.addDirectory(tableData.value);
  });
};
const exitEdit = () => {
  window.close();
};
//显示操作菜单
const contextMenuVisible = ref(false);
const subMenuVisible = ref({
  upinsert: false,
  downinsert: false,
  delete: false
});
const contextMenuPosition = ref({ top: 0, left: 0 });

const showContextMenu = (event: MouseEvent) => {
  console.log('没有chose')
  //阻止事件默认行为
  event.preventDefault();
  contextMenuVisible.value = true;
  contextMenuPosition.value = { top: event.clientY, left: event.clientX };
};

const showSubMenu = (menu: string) => {
  selectedMenuItem.value = menu;

  // 隐藏其他二级菜单
  for (const key in subMenuVisible.value) {
    if (key !== menu) {
      subMenuVisible.value[key] = false;
    } else {
      if (menu === "downinsert") {
        if (isEndingChapterFlag.value) {
          subMenuVisible.value[key] = false;
          subMenuVisible.value[menu] = false;
        } else {
          subMenuVisible.value[key] = true;
          subMenuVisible.value[menu] = true;
        }
        //  todo 从这开始判断是否选择或者答题是一个循环 ,如果是一个循环  就不能向下插入
      } else {
        subMenuVisible.value[menu] = true;
        adjustSubMenuPosition(menu);
      }
    }
  }
};

const components_number = ref(0);
const components_next_number = ref(1);

const valueFromParent = ref({
  moduleValue: "",
  moduleNext: ""
});
//  组件的在数组中的顺序排名
const componentSort = ref(0);

//  循环传入新的对象,以防子组件之间数据共享,然后被影响
const getComponentValue = componentId => {
  // 把组件的顺序传进去
  componentJson.value.chapter[componentId].sort = componentId;
  
  return { ...componentJson.value.chapter[componentId] }; // 返回一个新对象，避免共享引用
};

//快捷添加
const quickInsert = (module: string)=>{
  insertModule('文本', 'down','');
};

//新增组件产生的事件
const insertModule = (module: string, direction: string, nextId: string) => {
  if(!choosedNode.value.component && components.value.length > 0){
    alert('请选定一个节点！')
    return
  }
  if(choosedNode.value.component){
    if('down' === direction && (choosedNode.value.component.name === '选择' || choosedNode.value.component.name === '答题')){
      alert('选择或者答题组件不能直接向下插入')
      return
    }
  }
  
  const componentContent = componentMap[module];
  components_number.value = components_number.value + 1;//索引
  components_next_number.value = components_next_number.value + 1;//下一跳
  if (componentContent) {
    let moduleNextValue = '';
    //把不显示的元素删除
    const filteredComponents = components.value.filter(
      item => !item.isDisabled
    );
    if (filteredComponents.length === 0) {
      moduleNextValue = sort.value.toString() + "-" + components_next_number.value
      components.value.push({
        name: module, // 模块名称
        id: sort.value.toString() + "-" + components_number.value,
        componentSort: componentSort.value,
        moduleNext: moduleNextValue
      });

      componentJson.value.chapter.push({
        moduleId: sort.value.toString() + "-" + components_number.value,
        moduleType: componentMap[module].name,
        moduleValue: {},
        moduleNext: moduleNextValue
      });

      //指定sort
      selectedIndex.value = 0;
      isSelectedComponet.value = componentMap[module];
      choosedNode.value.index = components.value[0].componentSort;
      choosedNode.value.component = components.value[0];
    } else {
    
      let choseIndex = components.value.findIndex( item => item.id === choosedNode.value.component.id);

      if(''===nextId){
        nextId = sort.value.toString() + "-" + components_number.value;//下一跳全称
      }
         
      if (direction === "up") { 
        
        //找到上一个节点  6-5
        let choseNodeName = choosedNode.value.component.id;

        //从普通节点
        let lastNodeSort = componentJson.value.chapter.findIndex( item => item.moduleNext === choseNodeName
          && (item.moduleType !== 'Select'  && item.moduleType !=='QuestionAnswer')
        )
        //从选择和问答节点找
        if(lastNodeSort  === -1){
          componentJson.value.chapter.forEach(element => {
            if('Select' === element.moduleType || 'QuestionAnswer' === element.moduleType){
               element.moduleValue.value.forEach(item => {
                if(item.selectResult === choseNodeName){
                  lastNodeSort = componentJson.value.chapter.findIndex( x => x.moduleId === element.moduleId)
                }
              });
            }
          });
        }
        
        if(lastNodeSort !== -1){

          if("选择" === components.value[lastNodeSort].name || "答题" === components.value[lastNodeSort].name ){
            componentJson.value.chapter[lastNodeSort].moduleValue.value.forEach(item => {
                if(item.selectResult === choseNodeName){
                  item.selectResult = sort.value.toString() + "-" + components_number.value
                  item.selectContent = '指向->'+sort.value.toString() + "-" + components_number.value
                }
              });
          }else{
            //选中的节点
            components.value[lastNodeSort].moduleNext=nextId;
            componentJson.value.chapter[lastNodeSort].moduleNext=nextId;
           
          }
           moduleNextValue = components.value[choosedNode.value.component.componentSort]['id']
        
          
        }else{
           //头插
            moduleNextValue =  sort.value.toString() + "-" + components_next_number.value         
        }

        if("选择" === module || "答题" === module ){
          moduleNextValue = undefined
          //后面的节点全部删除
          lostMark(componentJson.value.chapter[choosedNode.value.component.componentSort].moduleId)
        }

        components.value.splice(choseIndex, 0, {
          name: module, // 模块名称
          id: sort.value.toString() + "-" + components_number.value,
          componentSort: componentSort.value,
          moduleNext:moduleNextValue
        });
        componentJson.value.chapter.splice(choseIndex, 0, {
          moduleId: sort.value.toString() + "-" + components_number.value,
          moduleType: componentMap[module].name,
          moduleValue: {},
          moduleNext: moduleNextValue,
          sort: componentSort.value
        });
        // 动态更新sort值
        components.value.forEach((element, index) => {
          element.componentSort = index;
        });
        componentJson.value.chapter.forEach((element, index) => {
          element.sort = index;
        });
        originComponents.value.forEach((element, index) => {
          element.sort = index;
        });
        componentSort.value = components.value.length;
       
      }
      if (direction === "down") {
        let nextLinkedIndex = components.value.findIndex( item => choosedNode.value.component.moduleNext === item.id);
  
        //插入操作
        if(components.value[nextLinkedIndex]){
          components.value[choseIndex].moduleNext=nextId;
          componentJson.value.chapter[choseIndex].moduleNext=nextId;
          if("选择" === module || "答题" === module ){
            moduleNextValue = undefined
            //后面的节点全部删除
            lostMark(componentJson.value.chapter[nextLinkedIndex].moduleId)
          }else{
            moduleNextValue = components.value[choosedNode.value.component.componentSort + 1]['id']
          }
        }else{
          //取选中点的指针
          nextId = componentJson.value.chapter[choseIndex].moduleNext;
          if("选择" === module || "答题" === module ){
            moduleNextValue = undefined
          }else{
            moduleNextValue =  sort.value.toString() + "-" + components_next_number.value
          }
        }

        components.value.splice(choseIndex + 1, 0, {
          name: module, // 模块名称
          id:nextId,
          componentSort: componentSort.value,
          moduleNext:moduleNextValue
        });
        componentJson.value.chapter.splice(choseIndex + 1, 0, {
          moduleId: nextId,
          moduleType: componentMap[module].name,
          moduleValue: {},
          moduleNext: moduleNextValue,
          sort: componentSort.value
        });
        // 动态更新sort值
        components.value.forEach((element, index) => {
          element.componentSort = index;
        });
        componentJson.value.chapter.forEach((element, index) => {
          element.sort = index;
        });
        originComponents.value.forEach((element, index) => {
          element.sort = index;
        });
      }
      let showId = components.value.findIndex( item => item.moduleNext === moduleNextValue);
      //指定sort
      selectedIndex.value = components.value[showId].componentSort;
      isSelectedComponet.value = componentMap[module];
      choosedNode.value.index = components.value[showId].componentSort;
      choosedNode.value.component = components.value[showId];
         
    }
  }
};


const insertSelectModule = (module: string, direction: string, nextId: string) => {

  const componentContent = componentMap[module];
  components_number.value = components_number.value + 1;//索引
  components_next_number.value = components_next_number.value + 1;//下一跳
  if (componentContent) {
    let moduleNextValue = '';
    //把不显示的元素删除
    const filteredComponents = components.value.filter(
      item => !item.isDisabled
    );
    let choseIndex = components.value.findIndex( item => item.id === choosedNode.value.component.id);   
    // nextId =  nextId = sort.value.toString() + "-" + components_number.value;//下一跳全称
    moduleNextValue =  sort.value.toString() + "-" + components_next_number.value
    components.value.splice(choseIndex + 1, 0, {
      name: module, // 模块名称
      id:nextId,
      componentSort: componentSort.value,
      moduleNext:moduleNextValue
    });
    componentJson.value.chapter.splice(choseIndex + 1, 0, {
      moduleId: nextId,
      moduleType: componentMap[module].name,
      moduleValue: {},
      moduleNext: moduleNextValue,
      sort: componentSort.value
    });
    // 动态更新sort值
    components.value.forEach((element, index) => {
      element.componentSort = index;
    });
    componentJson.value.chapter.forEach((element, index) => {
      element.sort = index;
    });
    originComponents.value.forEach((element, index) => {
      element.sort = index;
    });

    let showId = components.value.findIndex( item => item.moduleNext === moduleNextValue);
    //指定sort
    selectedIndex.value = components.value[showId].componentSort;
    isSelectedComponet.value = componentMap[module];  
  }
};

//删除节点
const deleteContainer = () => {
  const deleteIndex = choosedNode.value.index;

  let node = components.value[deleteIndex];
  let lastNodeIndex = components.value.findIndex( item => item.moduleNext === node.id);
  let nextNodeIndex = components.value.findIndex( item => item.id === node.moduleNext);

  //把上个节点的东西吓一跳弄一下
  if(lastNodeIndex >= 0){
    let nextSubSort = components_number.value + 1
    let nextId = sort.value.toString() + "-" + nextSubSort;
    components.value[lastNodeIndex].moduleNext=nextId;
    componentJson.value.chapter[lastNodeIndex].moduleNext=nextId;
    if('选择' === node.name || '答题' === node.name){
        //后面的节点全部删除
        lostMark(node.id)
    }else{
      if(nextNodeIndex >= 0){
        components.value[lastNodeIndex].moduleNext=components.value[nextNodeIndex].id;
        componentJson.value.chapter[lastNodeIndex].moduleNext=componentJson.value.chapter[nextNodeIndex].moduleId;
      }
    }
  }

  //如果上个节点是选择或者答题要把里面的选项值改了
  if(lastNodeIndex  === -1){
    componentJson.value.chapter.forEach(element => {
      if('Select' === element.moduleType || 'QuestionAnswer' === element.moduleType){
          element.moduleValue.value.forEach(item => {
          if(item.selectResult === choosedNode.value.component.id){
            lastNodeIndex = componentJson.value.chapter.findIndex( x => x.moduleId === element.moduleId)
            if(nextNodeIndex >= 0){
              item.selectResult=componentJson.value.chapter[nextNodeIndex].moduleId;
              item.selectContent='指向->'+componentJson.value.chapter[nextNodeIndex].moduleId;
            }else{
              item.selectResult = undefined
              item.selectContent= '暂无指向'
            }
          }
        });
      }
    });    
  }
  






  //删除元素
  components.value.splice(deleteIndex,1);
  componentJson.value.chapter.splice(deleteIndex,1);
 
  // 动态更新sort值
  components.value.forEach((element, index) => {
    element.componentSort = index;
  });
  componentJson.value.chapter.forEach((element, index) => {
    element.sort = index;
  });
  originComponents.value.forEach((element, index) => {
    element.sort = index;
  });

};

const hideSubMenu = (menu: string) => {
  subMenuVisible.value[menu] = false;
  selectedMenuItem.value = "";
  secondMenuItem.value = "";
};

const hideSecondMenu = (menu: string) => {
  selectedMenuItem.value = "";
  secondMenuItem.value = "";
};

const hideContextMenu = () => {
  contextMenuVisible.value = false;
};
// 点击手机容器的组件产生的事件
const componentClickEvent = (component: any) => {
  //指定sort
  selectedIndex.value = component.componentSort;
  isSelectedComponet.value = component;
  choosedNode.value.index = component.componentSort;
  choosedNode.value.component = component;
};

const scriptStore = useScriptStore();
const chapterStore = useChapterStore();
const choosedNode = ref({});

//右击事件
const handleRightEvent = (component, index) => {
 
  // 判断如果是下一章的组件 那么右击就不能显示子组件
  if (components.value[index]?.name === "章节") {

    if (componentJson.value.chapter[index].moduleValue.value === "1") {
      //   说明不能向下插入组件了
      console.log(subMenuVisible.value);
      subMenuVisible.value.downinsert = false;
      isEndingChapterFlag.value = true;
    } else {
      isEndingChapterFlag.value = false;
    }
  } else {

    isEndingChapterFlag.value = false;
  }

  choosedNode.value.index = index;
  choosedNode.value.component = component;
};

watch(
  () => directoryStore.directoryList,
  newDirectory => {
    options.value = newDirectory;
    options.value.forEach(item => {
      item.label = ` ${item.sequence} ${item.title}`;
    });
  },
  { deep: true }
);

// 切换章节的函数
const handleSelected = (sort, options) => {

  components.value = [];
  componentJson.value.chapter = [];
  isSelectedComponet.value = [];
  //   根据章节ID获取章节的json
  getContentByChapterId(options[sort - 1].id).then(res => {
    if (res.code === "0000") {
      const key = "chapter";
      let chapterInfo = {};
      originComponents.value = JSON.parse(res.data.content)["chapter"];
      if (isNull(res.data.content)) {
        res.data.content = {}; // 初始化为一个空对象
        res.data.content[key] = [];
        chapterInfo = JSON.stringify(res.data.content);
      } else {
        chapterInfo = res.data.content;
      }
      console.log(res.data.content);
      //  将获取的章节json存储到localstorage里面

      // 说明 localstorage 里面没有 第一章节的json数据
      let content = JSON.parse(chapterInfo);
      content[key] = content["chapter"];


      chapterStore.addChapter(content, key);
      componentSort.value = content[key].length;
      components_number.value = content[key].length;
      setObject();
    } else {
      message(res.message, {
        type: "error"
      });
    }
  });

  router.push({
    path: "/game-edit",
    query: { scriptId: scriptId, chapterId: sort }
  });
};


const setObject = () => {
  components.value = [];
  componentJson.value.chapter = [];
  //数据库存的原始数据
  if (originComponents.value.length > 0) {
    componentJson.value.chapter = originComponents.value;
    originComponents.value.forEach(item => {
      if (item.isDisabled) {
        components.value.push({
          name: moduleOptions[item.moduleType], // 模块名称
          id: item.moduleId,
          componentSort: item.sort,
          moduleNext: item.moduleNext,
          isDisabled: item.isDisabled
        });
      } else {
        components.value.push({
          name: moduleOptions[item.moduleType], // 模块名称
          id: item.moduleId,
          componentSort: item.sort,
          moduleNext: item.moduleNext
        });
      }
    });
  }else{
    console.log('ik')
  }
};


//问服务器要目录数据
const getDirectorybyScriptId = scriptId => {
  //   将数据存出到localstorage里面
  getDirectoryById(Number(scriptId)).then(res => {
    if (res.code === "0000") {
      options.value = res.data.list;
      if (options.value.length === 0) {
        //   说明这个游戏就没有创建目录,需要先创建目录
        message("请先创建剧本目录!!!", {
          type: "error"
        });
      } else {
        //   如果有目录 获取游戏目录的第一章节的后端json,并将这个json转成组件渲染到web端
        options.value.forEach(item => {
          item.label = ` ${item.sequence} ${item.title}`;
          const key = "chapter" + String(item.sort);
          if (item.sort === chapterId.value) {
            // 说明 localstorage 里面没有 第一章节的json数据
            getContentByChapterId(item.id).then(res => {
              if (res.code === "0000") {
                let content = JSON.parse(res.data.content);
                content[key] = content["chapter"];
                originComponents.value = content[key];
                // 存储到localstorage里面
                chapterStore.addChapter(content, key);
                componentSort.value = content[key].length;
                components_number.value = content[key].length;
                if (content[key].length === 0) {
                  components.value = [];
                  componentJson.value.chapter = [];
                  isSelectedComponet.value = [];
                } else {
                  setObject();
                }
              }
            });
          }
        });
      }
    }
  });
};

//生命周期函数 加载页面的时候执行的
onMounted(() => {
  if (!scriptId) {
    router.push("/error/404");
  } else {
    if (route.query.chapterId) {
      chapterId.value = Number(route.query.chapterId);
      sort.value = Number(route.query.chapterId);
    } else {
      chapterId.value = 1;
      sort.value = 1;
    }
    components.value = [];
    componentJson.value.chapter = [];
    isSelectedComponet.value = [];
    //   说明 有 scriptId  从持久化数据里面取出当前剧本的信息  这个获取的是这个游戏的 信息
    currentScriptInfo.value = scriptStore.getScriptById(scriptId);
    //   获取pinia的gameinfo数据,如果有数据就用数据库读取到的,如果没有就初始化一个
    getDirectorybyScriptId(scriptId);
    refreshDirectory(Number(scriptId));
  }
});
</script>
<style lang="scss" scoped>
.selected {
  background-color: #525252 !important;
}
.second-menu-selected {
  background-color: #525252 !important;
}

.component-index-id {
  padding-left: 30px;
  padding-top: 5px;
}
.gameContainer {
  padding-left: 53px;
  display: flex;
  gap: 20px;
}

.gameName {
  padding-top: 5px;
  font-weight: 500;
  font-size: 20px;
  font-family: "sans-serif";
  line-height: 26.52px;
  width: 200px;
}

.buttonClass {
  display: flex;
  justify-content: space-between;
  padding-right: 52px;
  gap: 20px;
}

.help_tips {
  width: 84px;
  margin: 19px auto 16px 639px;
}

.editor_component {
  padding: 0 !important;
  margin-left: 100px;
  flex-basis: 0;
  flex-grow: 1;
  max-width: 100%;
}

.context-menu {
  position: absolute;
  background-color: #232323;
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 5px;
  width: 120px;
  height: 165px;
  font-size: 18px;
  font-family: "sans-serif";
}

.menu-item {
  cursor: pointer;
  margin: 20px 12px 20px 12px;
  background-color: transparent; /* 设置菜单项的背景颜色为透明 */
  font-size: 18px;
  font-weight: 400;
  letter-spacing: 0px;
  line-height: 23.87px;
  color: rgba(229, 229, 229, 1);
  text-align: center;
  vertical-align: top;
}

.sub-menu {
  position: absolute;
  top: 0;
  right: -70px;
  background-color: #000000;
  border: 1px solid #ccc;
  padding: 5px;
  width: 70px;
  border-radius: 10px;
  overflow: auto;
}

.sub-menu-underinsert {
  position: absolute;
  top: 60px;
  right: -70px;
  background-color: #000000;
  border: 1px solid #ccc;
  padding: 5px;
  width: 70px;
  border-radius: 10px;
  overflow: auto;
}

.sub-menu div {
  background-color: transparent; /* 设置二级菜单的背景颜色为透明 */
}

.edit_area {
  background: #303031;
  height: 961px;
  color: white;
  display: flex;
  justify-content: space-between;
}

.edit_component_detail {
  width: 100px;
  margin-left: 100px;
}

.component_container {
  padding: 0 !important;
  flex-basis: 0;
  flex-grow: 1;
  max-width: 100%;

  .edit_component_detail {
  }
}

.preview_container {
  flex: 0 0 auto;
  width: auto;
  max-width: 100%;

  .part1 {
    width: 480px;
    padding-left: 130px;
    height: 50px;
  }
  :deep(.el-select__wrapper) {
    background-color: #383838;
    height: 40px;
    width: 380px;
    opacity: 1;
    border-radius: 10px;
    box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.25);
  }

  .part2 {
    justify-content: space-between;
    background: url("@/assets/phone_img.png") no-repeat 103px 0;
    background-size: 424px 843px;
    width: 527px;
    height: 770px;
    overflow-y: auto;
    scrollbar-width: none;

    .component_index {
      color: red;
    }

    .edit_component {
      display: flex;
      align-items: center;
      overflow-y: auto;
      .component_index {
        margin-left: 10px;
        margin-right: 30px;
        margin-top: 10px;
        border: solid black;
        background: black;
        color: white;
        border-radius: 10px;
        width: 100px;
        height: 40px;
        align-items: center;
        justify-content: center;
      }
    }
  }
}

.circle-contain {
  display: flex;
  padding-left: 10px;
  padding-bottom: 10px;
}

.circle-item {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
}

.native_container {
  background: #303031;
  color: white;
  display: flex;
  justify-content: space-between;
  padding-top: 20px;
  padding-bottom: 20px;
}

.menu-container {
  display: flex;
  justify-content: flex-end;
  gap: 20px;
  margin-bottom: 20px;
  margin: 0 0 0 0;
  font-family: "Microsoft Sans Serif";
  font-size: 20px;
  font-weight: 500;
  line-height: 26.52px;
}

.save-button {
  background-color: #ff8d1a;
  color: white;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
  border-radius: 7px;
  font-size: 16.18px;
  font-weight: 400;
  letter-spacing: 0px;
  line-height: 24.27px;
  text-align: center;
  vertical-align: top;
}

.sub-menu-up {
  position: absolute;
  bottom: 0;
  right: -70px;
  background-color: #000000;
  border: 1px solid #ccc;
  padding: 5px;
  width: 70px;
  border-radius: 10px;
  overflow: auto;
}

.exit-button {
  background-color: #444;
  color: white;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
  opacity: 1;
  border-radius: 7px;
}

/* 滚动条整体部分 */
::-webkit-scrollbar {
  width: 8px; /* 滚动条宽度 */
  height: 12px; /* 滚动条高度（对于横向滚动条） */
}

/* 滚动条轨道 */
::-webkit-scrollbar-track {
  background: #f1f1f1; /* 轨道背景色 */
  border-radius: 10px; /* 圆角 */
}

/* 滚动条滑块 */
::-webkit-scrollbar-thumb {
  background: #888; /* 滑块背景色 */
  border-radius: 10px; /* 圆角 */
}

/* 滑块在悬停时的样式 */
::-webkit-scrollbar-thumb:hover {
  background: #555; /* 悬停时滑块背景色 */
}
</style>
